package com.bee.bootstrap.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bee.bootstrap.resource.entity.Resource;
import com.bee.bootstrap.resource.service.IResourceService;
import com.bee.bootstrap.system.entity.Dictionary;
import com.bee.bootstrap.system.mapper.DictionaryMapper;
import com.bee.bootstrap.system.service.IDictionaryService;
import com.bee.common.core.constant.Constant;
import com.bee.common.core.enums.DictionaryTypeEnum;
import com.bee.common.core.enums.StatusEnum;
import com.bee.common.core.result.Result;
import com.bee.common.tools.httpclient.HttpClientResult;
import com.bee.common.tools.httpclient.HttpClientUtils;
import com.bee.common.tools.view.StringTools;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liekkas
 * @since 2018-04-10
 */
@Service
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary> implements IDictionaryService {

    @Autowired
    private IResourceService resourceServiceImpl;

    @Override
    public Result findPageView(Page<Dictionary> page, Dictionary dictionary) {
        EntityWrapper<Dictionary> entityWrapper = new EntityWrapper(dictionary);
        entityWrapper.orderBy("type").orderBy("sort");
        return Result.success(this.selectPage(page,entityWrapper));
    }

    public boolean persistenceAble(Dictionary dictionary){
        Dictionary condition=new Dictionary();
        dictionary.setType(dictionary.getType());
        dictionary.setDictionaryKey(dictionary.getDictionaryKey());
        dictionary.setStatus(StatusEnum.NORMAL.toString());
        Dictionary persistence=this.selectOne(new EntityWrapper<>(dictionary));
        return persistence==null||(dictionary.getId()!=null&&dictionary.getId().compareTo(persistence.getId())==0);
    }

    @Override
    public Result addDictionary(Dictionary dictionary) {
        if(!persistenceAble(dictionary)){
            return Result.fail("已存在类型["+dictionary.getType()+"]名称["+dictionary.getDictionaryKey()+"]的数据字典");
        }
        dictionary.setStatus(StatusEnum.NORMAL.toString());
        dictionary.setCreateTime(new Date());
        return Result.success(this.insert(dictionary));
    }

    @Override
    public Result updateDictionary(Dictionary dictionary) {
        if(!persistenceAble(dictionary)){
            return Result.fail("已存在类型["+dictionary.getType()+"]名称["+dictionary.getDictionaryKey()+"]的数据字典");
        }
        dictionary.setStatus(StatusEnum.NORMAL.toString());
        return Result.success(this.updateById(dictionary));
    }

    @Override
    public Result deleteDictionary(Long id) {
       Dictionary dictionary=this.selectById(id);
       dictionary.setStatus(StatusEnum.INVALID.toString());
       dictionary.setUpdateTime(new Date());
       return Result.success(this.updateById(dictionary));
    }

    @Override
    public Result selectTreeView() {
        List<Dictionary> all=this.selectList(new EntityWrapper<Dictionary>().eq("status", StatusEnum.NORMAL.toString()));
        List<Dictionary> parents=this.selectList(new EntityWrapper<Dictionary>().isNull("parent_id").eq("status", StatusEnum.NORMAL.toString()).orderBy("priority",true));
        parents.forEach(parent->{
            parent.setChildrensView(getChild(parent.getId(),all));
        });

        return Result.success(parents);
    }

    @Override
    public Result selectFormDictionary() {
        List<Dictionary> dictionaries=this.selectList(new EntityWrapper<Dictionary>().isNull("parent_id")
                .in("type",Arrays.asList(DictionaryTypeEnum.Form.toString(),DictionaryTypeEnum.Interface.toString()))
                .eq("status",StatusEnum.NORMAL.toString()));
        return Result.success(dictionaries);
    }

    @Override
    public Result selectFormTypeDictionarySub(Long parentId) {
        List<Dictionary> dictionaries=this.selectList(new EntityWrapper<Dictionary>().eq("parent_id",parentId)
                .eq("type", DictionaryTypeEnum.Form.toString())
                .eq("status",StatusEnum.NORMAL.toString()));
        Dictionary parent=this.selectById(parentId);
        parent.setChildrensView(dictionaries);
        return Result.success(parent);
    }

    @Override
    public List<Dictionary> selectFormTypeDictionarySub(Collection ids) {
        List<Dictionary> dictionaries=this.selectList(new EntityWrapper<Dictionary>().in("parent_id",ids)
                .eq("type", DictionaryTypeEnum.Form.toString())
                .eq("status",StatusEnum.NORMAL.toString()));
        return dictionaries;
    }

    @Override
    public Dictionary findByParentAndValue(List<Dictionary> dictionaries, Long parentId, String value) {
        for(Dictionary dictionary:dictionaries){
            if(dictionary.getParentId().compareTo(parentId)==0&&dictionary.getDictionaryValue().equals(value)){
                return dictionary;
            }
        }
        return null;
    }

    @Override
    public List<Dictionary> findCheckBoxElement(List<Dictionary> dictionaries, Long parentId, String values) {
        List<String> list=Arrays.asList(values.split(","));
        List<Dictionary> result=new ArrayList<Dictionary>();
        for(Dictionary dictionary:dictionaries){
            for(String value:list){
                if(dictionary.getParentId().compareTo(parentId)==0&&dictionary.getDictionaryValue().equals(value)){
                    result.add(dictionary);
                }
            }
        }
        return result;
    }


    @Override
    public Result findTranslate(String text) {
        try {
            HttpClientResult result=HttpClientUtils.doHttpsGet(Constant.TRANSLATE_URL+text,null,null);
            if(200==result.getCode()){
                String translate=result.getContent().get("text").toString().toLowerCase()
                        .replace("\"","").replace("[","").replace("]","").replace(" ","_");
                return Result.success("", StringTools.underline2Camel(translate,true));
            }
            return Result.fail("翻译服务不能使用");
        } catch (Exception e) {
            return Result.fail("翻译服务不能使用");
        }
    }

    @Override
    public Result findInterfaceResource(Long id) {
        Dictionary dictionary=this.selectOne(new EntityWrapper<Dictionary>()
                .eq("id",id).eq("type",DictionaryTypeEnum.Interface.toString())
                .eq("status",StatusEnum.NORMAL.toString()));
        if(dictionary!=null&& StringUtils.isNotBlank(dictionary.getDictionaryValue())){
            Resource resource=resourceServiceImpl.selectById(dictionary.getDictionaryValue());
            return Result.success(resource);
        }
        return Result.fail("未定义该数据接口");
    }

    /**
     * 递归查找子数据
     * @param id
     * @param all
     * @return
     */
    private List<Dictionary> getChild(Long id, List<Dictionary> all) {
        List<Dictionary> childrens=new ArrayList<Dictionary>();
        all.forEach(dictionary -> {
            if(dictionary.getParentId()!=null&&dictionary.getParentId().compareTo(id)==0){
                childrens.add(dictionary);
            }
        });
        //子资源的再遍历一次
        childrens.forEach(children->{
            children.setChildrensView(getChild(children.getId(),all));
        });
        Collections.sort(childrens, new Comparator<Dictionary>() {
            @Override
            public int compare(Dictionary o1, Dictionary o2) {
                if(o1.getPriority()!=null&&o2.getPriority()!=null)
                    return o1.getPriority().compareTo(o2.getPriority());
                else
                    return 0;
            }
        });//排序
        if(childrens.size()==0){
            return new ArrayList<Dictionary>();
        }
        return childrens;
    }
}
